package com.cyneck.demo.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.net.www.protocol.https.HttpsURLConnectionImpl;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URL;

/**
 * <p>Description:  稿定科技 https://www.gaoding.com/koutu</p>
 *
 * @author Eric Lee
 * @version v1.0.0
 * @since 2020/9/15 16:22
 **/
@Component
public class GaodingClientUtil {


    /**
     * 搞定抠图ak
     */
    @Value("${gaoding.ak}")
    private String ak;

    /**
     * 搞定抠图sk
     */
    @Value("${gaoding.sk}")
    private String sk;


    public String getHMAC(String data, String key) throws Exception {
        String HMAC_SHA1_ALGORITHM = "HmacSHA1";

        SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(),
                HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signinKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return new String(Base64.encodeBase64(rawHmac));
    }

    public HttpEntity cutoutPhoto(String imageUrl) throws Exception {
        String httpMethod = "POST";
        String uri = "/api/v10/image/";
        String queryString = "";
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("url", imageUrl);
        Long timestamp = System.currentTimeMillis() / 1000;
        String requestRaw = StringUtils.join(
                new String[]{httpMethod, "@",
                        uri, "@",
                        queryString, "@",
                        timestamp.toString(), "@",
                        jsonBody.toJSONString()}, "");

        String signature = getHMAC(requestRaw, sk);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("https://matting-api.dancf.com/api/v10/image");
        CloseableHttpResponse response = null;
        try {
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("X-Timestamp", timestamp.toString());
            httpPost.addHeader("X-AccessKey", ak);
            httpPost.addHeader("X-Signature", signature);
            httpPost.setEntity(new StringEntity(jsonBody.toString()));
            response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            System.out.println(":" + response.getStatusLine());
            return responseEntity;

        } finally {
            try {
                //
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpsURLConnectionImpl conn = (HttpsURLConnectionImpl) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }


        System.out.println("info:" + url + " download success");

    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


}
